package com.eflow.model.flowable.converter;

import cn.hutool.core.bean.BeanUtil;
import com.eflow.model.domain.EflowUser;
import com.eflow.model.domain.ScriptProcessVariable;
import com.eflow.model.e.BpmConst;
import com.eflow.model.flowable.entity.ScriptEntity;
import com.eflow.model.flowable.model.UserElement;
import com.eflow.model.flowable.model.e.UserTypeEnum;
import com.eflow.model.groovy.GroovyScriptEngine;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hui se
 * @description
 * @create 2021-03-05 18:21
 **/
@Component
public class UserScriptConverter extends BaseUserListConverter implements BpmConst {

    @Autowired
    private GroovyScriptEngine groovyScriptEngine;

    @Override
    List<EflowUser> list(UserElement userElement, String loginUser, ProcessDefinition processDefinition, String processInstanceId, String activityId, Map<String,Object> var) {
        Map<String,Object> data = (Map)userElement.getData();
        ScriptEntity scriptEntity = new ScriptEntity();
        BeanUtil.fillBeanWithMap(data,scriptEntity,true);
        ScriptProcessVariable scriptProcessVariable = new ScriptProcessVariable();
        scriptProcessVariable.setProcessInstanceId(processInstanceId);
        scriptProcessVariable.setUserElement(userElement);
        scriptProcessVariable.setUser(loginUser);
        scriptProcessVariable.setProcessDefinition(processDefinition);
        scriptProcessVariable.setVar(var);
        HashMap<String, Object> v = new HashMap<>();
        v.put(SCRIPT_VAR_NAME,scriptProcessVariable);
        Object object = groovyScriptEngine.executeObject(scriptEntity.getText(), v);
        if(!(object instanceof List)){
            throw new RuntimeException("该脚本不是返回一个用户列表："+scriptEntity.getText());
        }
        return  (List)object;
    }

    @Override
    UserTypeEnum getUserType() {
        return UserTypeEnum.SCRIPT;
    }
}
